package com.jxs.android.ges;

import java.io.IOException;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.xmlpull.v1.XmlPullParserException;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;

import com.jxs.android.ges.data.UserInfo;
import com.jxs.android.ges.db.CustomerParamHolder;
import com.jxs.android.ges.util.CryptUtil;
import com.jxs.android.soap.BuWebService;
import com.jxs.android.soap.IWebService;
import com.jxs.android.util.MemoryUtil;
import com.jxs.android.util.StartHelper;
import com.jxs.android.util.StringUtils;
import com.jxs.android.util.SysUpdateHolder;
import com.jxs.android.util.VersionHolder;
import com.jxs.android.weiget.BuAlertDailog;
import com.jxs.android.weiget.BuLoadingDailog;
import com.jxs.android.weiget.LockPatternView;

@SuppressLint("HandlerLeak")
public class Login extends AbstractActivity {

	private LockPatternView lockPatternView;
	private Context context;
	private BuLoadingDailog buLoadingDailog;
	private String imsi = "460036520427761";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		context = this;
		initLoadingView();
		super.initTopBar(savedInstanceState, R.layout.bu_login);
		TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		imsi = null == tm.getSubscriberId() ? "" : tm.getSubscriberId();
		if (StringUtils.isEmpety(imsi)) {
			errorMsgPop(R.string.error_not_has_sim, new BuAlertDailog.IPhoneAlertDailog() {

				@Override
				public void okLogic(Dialog dialog) {
					finish();
				}

				@Override
				public String getOkText(Context context) {
					return null;
				}
			});
		}
		// imsi = "460036191894981";// 1new
		// imsi = "460036191040204";// 2new

		lockPatternView = (LockPatternView) this.findViewById(R.id.lock_pattern);
		lockPatternView.setCheckConfirmListener(new LockPatternView.ICheckConfrim() {

			@Override
			public void onLockPattern(boolean bInit, boolean matched) {
				if (bInit) {
					buLoadingDailog.showLoading(R.string.tip_user_login);
					login(lockPatternView.getPathWord());
					lockPatternView.resetGraphData();
					lockPatternView.resetState();
				}
			}
		}, this);
	}

	private void initLoadingView() {
		buLoadingDailog = new BuLoadingDailog(context);
		buLoadingDailog.setLoadingListener(new BuLoadingDailog.LoadingListener() {

			@Override
			public void okLogic(Dialog dialog) {
				dialog.dismiss();
			}

			@Override
			public String getOkText(Context context) {
				return getString(R.string.prompt_confirm);
			}
		});
	}

	private void login(final String password) {
		final CryptUtil crypt = CryptUtil.getInstance();
		new Thread(new Runnable() {

			@Override
			public void run() {
				String wsdl_url = GesApplication.WSDL_URL;// wsdl
				String namespace = GesApplication.WSDL_NAME_SPACE;// namespace
				String methodName = "login";// 要调用的方法名称
				SoapObject request = new SoapObject(namespace, methodName);
				request.addProperty("password", crypt.encryptAES(password, CryptUtil.getKey()));

				request.addProperty("imsiCode", crypt.encryptAES(imsi, CryptUtil.getKey()));
				request.addProperty("imeiCode", crypt.encryptAES(((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).getDeviceId(), CryptUtil.getKey()));
				request.addProperty("systemVersion", android.os.Build.VERSION.RELEASE);
				request.addProperty("clientVersion", VersionHolder.getVersionName(context));
				request.addProperty("longitude", "105");
				request.addProperty("latitude", "44");
				BuWebService webService = new BuWebService(wsdl_url, request);
				webService.setDoNet(false);
				webService.requestWSDL(new IWebService() {
					@Override
					public void logic(SoapSerializationEnvelope envelope) throws IOException, XmlPullParserException {
						SoapObject response = (SoapObject) envelope.getResponse();
						paserLogin(response, password);
					}

					@Override
					public void error(String message, Exception e) {
						Message msg = new Message();
						msg.what = ERROR_MSG;
						msg.obj = message;
						handler.sendMessage(msg);
					}
				});
			}
		}).start();
	}

	private void paserLogin(SoapObject soapObject, String password) {
		String status = soapObject.getPropertySafelyAsString("status");
		// String status = soapObject.getPropertySafelyAsString("result");
		if ("-1".equals(status)) {
			Message msg = new Message();
			msg.what = UPDATE_VERSION;
			String objs[] = new String[2];
			objs[0] = getString(R.string.error_has_new_version);
			objs[1] = soapObject.getPropertySafelyAsString("url");
			msg.obj = objs;
			handler.sendMessage(msg);
		} else if ("2".equals(status)) {
			Message msg = new Message();
			msg.what = ERROR_MSG;
			msg.obj = getString(R.string.error_password);
			handler.sendMessage(msg);
		} else if ("0".equals(status)) {
			Message msg = new Message();
			msg.what = ERROR_MSG;
			msg.obj = getString(R.string.error_not_has_this_user);
			handler.sendMessage(msg);
		} else if ("1".equals(status)) {
			UserInfo userInfo = new UserInfo();

			SoapObject userJson = (SoapObject) soapObject.getProperty("user");

			userInfo.setCdma_no(userJson.getPropertySafelyAsString("cdma_no"));// 手机号码

			userInfo.setImsi(userJson.getPropertySafelyAsString("imsi"));// 手机串号

			userInfo.setLatn_id(userJson.getPropertySafelyAsString("latn_id"));// 本地网ID

			userInfo.setLatn_name(userJson.getPropertySafelyAsString("latn_name"));// 本地网名称

			userInfo.setIndustry_type_id(userJson.getPropertySafelyAsString("industry_type_id"));// 行业ID

			userInfo.setIndustry_type_name(userJson.getPropertySafelyAsString("industry_type_name"));// 行业名称

			userInfo.setName(userJson.getPropertySafelyAsString("name"));// 姓名

			userInfo.setStaff_no(userJson.getPropertySafelyAsString("staff_no"));// 员工ID

			userInfo.setTicket(userJson.getPropertySafelyAsString("ticket"));// 用户登陆成功后，获得的访问会话的ticket，调用功能接口需要填写该参数；【重要】

			userInfo.setPassword(password);
			GesApplication.setUserInfo(userInfo);
			handler.sendEmptyMessage(LOGIN_ON);
		}
	}

	private int LOGIN_ON = 0x110;
	private int UPDATE_VERSION = 0x111;
	private int ERROR_MSG = 0x112;

	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (MemoryUtil.isCurrentActivity(Login.class)) {
				if (null != buLoadingDailog && buLoadingDailog.isShowing()) {
					buLoadingDailog.dismiss();
				}
				if (msg.what == LOGIN_ON) {
					if (CustomerParamHolder.isFirstRunOvered()) {
						StartHelper.startActivity(new Intent(context, LaucherMain.class));
					} else {
						CustomerParamHolder.saveOrUpdate(CustomerParamHolder.Key.IS_FIRST_RUN_OVERED, CustomerParamHolder.Value.PARAM_YES, imsi);
						Intent intent = new Intent(context, FeatureGuide.class);
						intent.putExtra("hinde", true);
						StartHelper.startActivity(intent);
					}
					finish();
				} else if (msg.what == ERROR_MSG) {
					errorMsgPop(msg.obj.toString());
				} else if (msg.what == UPDATE_VERSION) {
					String objs[] = (String[]) msg.obj;
					SysUpdateHolder.showUpdataDialog(Login.this, objs[0], "下载新版本", objs[1], new SysUpdateHolder.UpdateCancelListern() {
						@Override
						public void cancel() {
							finish();
						}
					});
				}
			}
		}

	};

}